﻿#ifndef __SS_POOL_H__
#define __SS_POOL_H__
#include "./ssDoublyList.h"

namespace StarSeeker
{

class ssPool
{
public:
	//分配对象
	void* Malloc(u32 size)
	{
		if (size<=64)
			return m_list64.Allot();
		else if (size <= 256)
			return m_list256.Allot();
		else if (size <= 512)
			return m_list512.Allot();
		else if (size <= 1024)
			return m_list1k.Allot();
		else if (size <= 131072)
			return m_list128k.Allot();
		else if (size <= 524288)
			return m_list512k.Allot();
		else if (size <= SS_1MB)
			return m_list1m.Allot();
		else
			return ::malloc(size);
	}
	//回收对象
	bool Free(void* pt)
	{
		if (pt)
		{
			if (size <= 64)
				m_list64.Erase(pt);
			else if (size <= 256)
				m_list256.Erase(pt);
			else if (size <= 512)
				m_list512.Erase(pt);
			else if (size <= 1024)
				m_list1k.Erase(pt);
			else if (size <= 131072)
				m_list128k.Erase(pt);
			else if (size <= 524288)
				m_list512k.Erase(pt);
			else if (size <= SS_1MB)
				m_list1m.Erase(pt);
			else
				::free(pt);
			return true;
		}
		return false;
	}
	//释放没有使用的内存
	void Release()
	{
		m_list64.ReleaseFreeNode();
		m_list256.ReleaseFreeNode();
		m_list512.ReleaseFreeNode();
		m_list1k.ReleaseFreeNode();
		m_list128k.ReleaseFreeNode();
		m_list512k.ReleaseFreeNode();
		m_list1m.ReleaseFreeNode();
	}
	//内存是否属于池
	bool IsFrom(T* pt)
	{
		if (pt)
		{
			if (size <= 64)
				return m_list64.DataIsFrom(pt);
			else if (size <= 256)
				return m_list256.DataIsFrom(pt);
			else if (size <= 512)
				return m_list512.DataIsFrom(pt);
			else if (size <= 1024)
				return m_list1k.DataIsFrom(pt);
			else if (size <= 131072)
				return m_list128k.DataIsFrom(pt);
			else if (size <= 524288)
				return m_list512k.DataIsFrom(pt);
			else if (size <= SS_1MB)
				return m_list1m.DataIsFrom(pt);
			else
				return true;
		}
		return false;
	}
private:
	ssDoublyList<64>			m_list64;
	ssDoublyList<256>			m_list256;
	ssDoublyList<512>			m_list512;
	ssDoublyList<1024>			m_list1k;
	ssDoublyList<131072>		m_list128k;
	ssDoublyList<524288>		m_list512k;
	ssDoublyList<SS_1MB>		m_list1m;
};

template<typename T>
class ssMutexssPool
{
public:
	//分配对象
	T* Malloc()
	{
		T* tmp = 0;
		m_lock.Lock();
		tmp = m_pool.Malloc();
		m_lock.Unlock();
		return tmp;
	}
	//回收对象
	bool Free(T* pt)
	{
		bool tmp = false;
		m_lock.Lock();
		tmp = m_pool.Free(pt);
		m_lock.Unlock();
		return tmp;
	}
	//释放没有使用的内存
	void Release()
	{
		m_lock.Lock();
		m_pool.Release();
		m_lock.Unlock();
	}
	//内存是否属于池
	bool IsFrom(T* pt)
	{
		return m_pool.IsFrom(pt);
	}
private:
	ssPool				m_pool;
	ssAtomicLock		m_lock;
};

}
#endif
